﻿using System;
using System.Diagnostics;
using System.Net;
using System.IO;
using System.Text;
using System.Drawing;
using System.Threading.Tasks;
using WxLib.Core.Util;
using WxLib.Core.Exceptions;

namespace WxLib.Core.RequestHandlers
{
    /// <summary>
    ///  简单的实现请求图片
    /// </summary>
    public class ImageRequestHandler : IImageRequestHandler
    {
        private readonly TraceSource _trace = new TraceSource("WxLib", SourceLevels.All);

        /// <summary>
        ///  请求并返回图片数据
        /// </summary>
        /// <param name="uri">请求地址</param>
        /// <returns>图片数据</returns>
        public async Task<byte[]> RequestImageDataAsync(Uri uri)
        {
            _trace.TraceEvent(TraceEventType.Verbose, 0, "ImageRequestHandler:Start");
            var request = HttpRequestHelper.CreateRequest(uri);
            byte[] buffer;
            try
            {
                buffer = await HttpRequestHelper.GetResponseBufferAsync(request).ConfigureAwait(false);
            }
            catch (WebException e)
            {
                throw new WxLibWebException("A request caused a WebException.", e.InnerException as WebException);
            }
            _trace.TraceEvent(TraceEventType.Verbose, 0, "ImageRequestHandler:Complete");
            return buffer;
        }

        /// <summary>
        ///  请求图片并将其保存到文件。
        /// </summary>
        /// <param name="uri">请求地址</param>
        /// <param name="file">文件保存路径</param>
        /// <returns>异步任务</returns>
        public Task RequestImageAsync(Uri uri, string file)
        {
            using (var client = new WebClient())
            {
                return client.DownloadFileTaskAsync(uri, file);
            }
        }

        /// <summary>
        ///  请求并返回图片数据
        /// </summary>
        /// <param name="uri">请求地址</param>
        /// <param name="postString"></param>
        /// <returns>图片数据</returns>
        public async Task<byte[]> PostRequestImageDataAsync(Uri uri, string postString)
        {
            _trace.TraceEvent(TraceEventType.Verbose, 0, "ImageRequestHandler:Start");
            var request = HttpRequestHelper.CreateRequest(uri);
            request.Method = "POST";
            HttpRequestHelper.AddPostData(request, postString);
            byte[] buffer;
            try
            {
                buffer = await HttpRequestHelper.GetResponseBufferAsync(request).ConfigureAwait(false);
            }
            catch (WebException e)
            {
                throw new WxLibWebException("A request caused a WebException.", e.InnerException as WebException);
            }
            _trace.TraceEvent(TraceEventType.Verbose, 0, "ImageRequestHandler:Complete");
            return buffer;
        }

    }
}